package exam.driver.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import exam.common.util.NullCheckUtil;
/**
 * <p>JdbcManagerConnection</p>
 * <p>Class quản lý kết nối đến server</p>
 * @author PHONGTN
 * @version 17/4/2012
 */
public class JdbcManagerConnection {
	// connection
	protected Connection connection;
	// jdbcConnection
	protected JdbcConnection jdbcConnection;
	
	/**
	 * Constructor
	 * @param driver
	 * @param url
	 */
	public JdbcManagerConnection(JdbcConnection jdbcConnection) {
		this.jdbcConnection = jdbcConnection;
		this.loadDriver();
	}
	/**
	 * Constructor
	 */
	public JdbcManagerConnection() {}
	
	/**
	 * loadDriver
	 */
	private void loadDriver() {
		try {
			Class.forName(this.jdbcConnection.getDriver());
		} catch (ClassNotFoundException e) {
			System.err.println("Error: JdbcManagerConnection#loadDriver");
			System.exit(1);
		}
	}
	
	/**
	 * openConnect: Kết nối database
	 */
	public void openConnect() {
		try {
			connection = DriverManager.getConnection(
					this.jdbcConnection.getUrl(),
					this.jdbcConnection.getUsername(),
					this.jdbcConnection.getPassword());
			connection.setAutoCommit(false);
		} catch (SQLException e) {
			System.err.println("Error: JdbcManagerConnection#openConnect");
			System.exit(1);
		}
	}
	
	/**
	 * isConnected: kiểm tra kết nối chưa
	 */
	public boolean isConnected() {
		return NullCheckUtil.isNotNull(connection);
	}
	
	/**
	 * isClosed: kiểm tra đống kết nối chưa
	 */
	public boolean isClosed() {
		return NullCheckUtil.isNUll(connection);
	}
	
	/**
	 * getConnection: trả về 1 kết nối đến server 
	 */
	public Connection getConnection() {
		return connection;
	}
	
	/**
	 * backup: khôi phục dữ liệu
	 */
	public void backup() {
		try {
			connection.rollback();
		} catch (SQLException e) {
			System.err.println("Error: JdbcManagerConnection#backup");
			e.getMessage();
		}
	}
	
	/**
	 * closeConnection: đóng kết nối
	 */
	public void closeConnection() {
		if(this.isConnected()) {
			try {
				connection.commit();
				connection.close();
				connection = null;
			} catch (SQLException e) {
				System.err.println("Error: JdbcManagerConnection#closeConnection");
				e.getMessage();
			}
		}
	}
}
